#include "cpuinfobrowser.h"
#include "ui_cpuinfobrowser.h"
#include "cpurankitem.h"
#include "cpurankitemdelegate.h"
#include "cpurankviewmodel.h"

#include <httpclient.h>
#include <qrcutil.h>

#include <QListWidgetItem>
#include <QProgressDialog>
#include <QStandardItemModel>
#include <QtConcurrent>

CpuInfoBrowser::CpuInfoBrowser(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CpuInfoBrowser)
{
    ui->setupUi(this);

    // ui->webView->load(QUrl("https://cpu.bmcx.com/6382_5493__cpu/"));
    connect(ui->webView, &QWebEngineView::loadProgress, this, [=](int progress){
        ui->progressBar->setValue(progress);
        if (progress == 100) {
            ui->stackedWidget->setCurrentWidget(ui->stack_fail);
        }
    });

    connect(ui->webView, &QWebEngineView::loadFinished, this, [=](bool finished){

        if (finished) {
            ui->webView->page()->runJavaScript(QR("://javascript.js"));
            ui->stackedWidget->setCurrentWidget(ui->webView);
        } else {
            ui->stackedWidget->setCurrentWidget(ui->stack_fail);
        }

        // static bool zoom_changed = false;
        // qreal currentZoom = ui->webView->page()->zoomFactor();
        // setWindowTitle(QString("currentZoom = %1  > 1.5").arg(currentZoom));

//        if (!zoom_changed) {
//            zoom_changed = true;
//            if (currentZoom == 1) {
//                ui->webView->setZoomFactor(1.5);
//            }
//        }
    });

    // -----------------

    CpuRankViewModel *cpu_rank_model = new CpuRankViewModel;
    CpuRankItemDelegate *cpu_rank_delegate = new CpuRankItemDelegate;
    ui->cpu_rank_list->setModel(cpu_rank_model);
    ui->cpu_rank_list->setItemDelegate(cpu_rank_delegate);

    // [2] 实现模型数据过滤
    QSortFilterProxyModel *cpu_rank_proxy_model = new QSortFilterProxyModel(this);
    cpu_rank_proxy_model->setSourceModel(cpu_rank_model); // 绑定源模型
    cpu_rank_proxy_model->setFilterRole(CpuRankViewModel::CpuRankMingCheng); // 指定过滤角色
    cpu_rank_proxy_model->setFilterCaseSensitivity(Qt::CaseInsensitive);
    ui->cpu_rank_list->setModel(cpu_rank_proxy_model);

    connect(ui->cpu_filter, &QLineEdit::textChanged, [=](const QString &text){
        // 同步过滤条件到代理模型
        if (text.isEmpty()) {
            cpu_rank_proxy_model->setFilterFixedString(text); // 清空过滤
        } else {
            cpu_rank_proxy_model->setFilterWildcard(text); // 设置通配符过滤（支持模糊匹配）
        }
    });

    // -----------------

    connect(cpu_rank_delegate, &CpuRankItemDelegate::switchIdChagned, this, [=](const QString &id, bool switched){
        if (switched) {
            m_cpuids.append(id);
        } else {
            m_cpuids.removeAll(id);
        }
        if (not m_cpuids.isEmpty()) {
            ui->stackedWidget->setCurrentWidget(ui->stack_loading);
            ui->webView->load(QUrl(QString("https://cpu.bmcx.com/%1__cpu/").arg(m_cpuids.join("_"))));
        }
    });

    // --------------

    QtConcurrent::run([=]() {
        Response resp = HttpClient::instance().get("https://cpu.bmcx.com/web_system/bmcx_com_www/system/file/cpu/get_data/?lx=cpu&s=1&e=999999");

        if (resp.ok()) {
            for (auto var : resp.toList()) {
                cpu_rank_model->append(new CpuRankInfo(var.toMap()));
            }
            // 请求完成后回到主线程更新UI
            QMetaObject::invokeMethod(this, [=](){ emit cpu_rank_model->layoutChanged(); }, Qt::QueuedConnection);
        }
    });

    // --------------
    ui->splitter->setSizes(QList<int>() << width() / 2 << width() / 2);

    load_cpu_rank_list();
}

CpuInfoBrowser::~CpuInfoBrowser()
{
    delete ui;
}

void CpuInfoBrowser::load_cpu_rank_list()
{


}

//void CpuInfoBrowser::reply_cpu_rank_resp(Response resp)
//{
//    reply_cpu_rank_list_progress(resp.toList());
//}

//void CpuInfoBrowser::reply_cpu_rank_list_progress(const QVariantList &list)
//{
//    QProgressDialog progress("Loading CPU data...", "Cancel", 0, 0, this);
//    progress.setWindowModality(Qt::WindowModal);
//    progress.show();
//    progress.setRange(0, list.count());

//    uint count = 0;

//    QList<std::pair<QListWidgetItem *, CpuRankItem *>> items;
//    foreach (auto var, list) {
//        items.append(reply_cpu_rank_list_item(var.toMap()));
//        progress.setValue(count++);
//    }
//    progress.close();

//    foreach (auto item, items) {
//        reply_cpu_rank_list_item(item.first, item.second);
//    }
//}

//std::pair<QListWidgetItem *, CpuRankItem *> CpuInfoBrowser::reply_cpu_rank_list_item(const QVariantMap &map)
//{
//    auto item = new QListWidgetItem;
//    auto widget = CpuRankItem::fromMap(map);

//    item->setSizeHint(widget->sizeHint());
//    return {item, widget};
//}

//void CpuInfoBrowser::reply_cpu_rank_list_item(std::pair<QListWidgetItem *, CpuRankItem *> item)
//{
//    reply_cpu_rank_list_item(item.first, item.second);
//}

//void CpuInfoBrowser::reply_cpu_rank_list_item(QListWidgetItem *item, CpuRankItem *widget)
//{
//    item->setSizeHint(widget->sizeHint());
//    ui->cpu_list_widget->addItem(item);
//    ui->cpu_list_widget->setItemWidget(item, widget);
//}

//void CpuInfoBrowser::reply_cpu_rank_list(const QVariantList &list)
//{
//    for (auto var : list) {
//        std::pair<QListWidgetItem *, CpuRankItem *> item
//                = reply_cpu_rank_list_item(var.toMap());
//        reply_cpu_rank_list_item(item);
//    }
//}

//void CpuInfoBrowser::reply_cpu_rank_list(const QNetworkReply *reply)
//{
//    Response resp(reply);
//    if (resp.ok()) {
//        reply_cpu_rank_list(resp.toList());
//    } else {
//        qDebug() << "Error:" << reply->errorString();
//    }
//}

void CpuInfoBrowser::cpu_search_slot(const QString &arg1)
{

}

